<script setup lang="ts">
import {ref, computed, defineProps} from 'vue'
import {orderSingleInfo,pay} from '../api/order.ts'
import { parseDelivery} from "../utils";
import {discount, singleCouponInfo, useCoupon} from "../api/coupon.ts";
import {ElTable} from "element-plus";

const storeId = ref()
const orderId = ref()
const couponId = ref<number[]>([])
const chosenTypes = ref<number[]>([])
const chosenGroupId = ref<number[]>([])
const productName = ref('')
const price = ref()
const quantity = ref()
const delivery = ref('')
const currentRow = ref<coupon[]>([])
const use = ref('1')
const priceSum = computed(() => price.value * quantity.value)
const priceFin = ref()
const emit = defineEmits(['finish'])
const couponList = ref<coupon[]>([])
const newList = ref<coupon[]>([])
const payDisable = computed(() => use.value === '0' && currentRow.value.length === 0)
const props = defineProps<{
  orderId : number,
}>()
const newKey = ref(1)
const multipleTableRef = ref<InstanceType<typeof ElTable>>()
orderId.value = props.orderId

orderSingleInfo(orderId.value).then(res =>{
  productName.value = res.data.result.commodityName
  price.value = res.data.result.price
  quantity.value = res.data.result.quantity
  delivery.value = res.data.result.deliveryMethod
  productName.value = res.data.result.commodityName
  priceFin.value = priceSum.value
  storeId.value = res.data.result.storeID
  getUseableCoupon()
})
function getUseableCoupon2(){
  getUseableCoupon()
}
const toggleSelection = () =>{
  console.log('勾选')
  setTimeout(() => {
    currentRow.value.forEach((row) => {
      const matchedRow = couponList.value.find(dataRow => dataRow.id === row.id);
      console.log(matchedRow)
      if (matchedRow) {
        multipleTableRef.value!.toggleRowSelection(matchedRow, true);
      }
    });
  }, 100);
}
function getUseableCoupon() {
  useCoupon({
    storeId : storeId.value,
    price: priceFin.value,
    chosenTypes : chosenTypes.value

  }).then(res => {
    newList.value = []

    for(let i of couponList.value){
      if(currentRow.value.includes(i)){
        newList.value.push(i)
      }
    }
    for (let i of res.data.result) {
      singleCouponInfo(i.couponGroupId).then(res => {
        const target = ref('')
        const type = ref('')
        if (res.data.result.couponScope === 'GLOBAL') {
          target.value = "所有商店"
        } else {
          target.value = "仅限于本商店"
        }
        if (res.data.result.couponType === 'SPECIAL') type.value = "蓝鲸券"
        else if(res.data.result.couponType === 'FULL_REDUCTION') type.value = '满减券' + '(满' + res.data.result.fullAmount + "元减" + res.data.result.discountAmount + '元)'
        else type.value = '无门槛券' + '(立减' + res.data.result.discountAmount + '元)'
        newList.value.push({id: i.id, groupId: res.data.result.id, type: type.value, scope: target.value})
      })
    }
    console.log('更新数据开始')
    if(couponList.value != newList.value) {
      couponList.value = newList.value

    }
    console.log('更新数据结束')
    newKey.value = Math.random()
    toggleSelection()
  })
}
function payOrder(){
  if(use.value === '1'){
    console.log(77)
    couponId.value = []
  }
  else{
    couponId.value = []
    for(let i of currentRow.value){
      console.log(99)
      console.log(i.id)
      couponId.value.push(i.id)
    }
  }
  console.log(couponId.value)
  pay({
    orderID : orderId.value,
    couponID : couponId.value
  }).then(res =>{
    if(res.data.code === '000'){
      ElMessage({
        message: "支付成功！",
        type: 'success',
        center: true,
      })
      emit('finish')
    }
    else{
      ElMessage({
        message: res.data.msg,
        type: 'error',
        center: true,
      })
    }
    // const div = document.createElement('div');
    // div.innerHTML = res.data
    // const formElement = div.querySelector('form[name="punchout_form"]') as HTMLFormElement;
    // const newWindow = window.open('', '_blank');
    // if (newWindow) {
    //   newWindow.document.body.appendChild(formElement);
    //   formElement.submit()
    // }

  })

}

interface coupon {
  id : number
  groupId : number
  type: string
  scope: string
}

function handleChange(val: coupon[]){
    currentRow.value = val
    chosenGroupId.value = []
    chosenTypes.value = []
    for (let i of val) {
      chosenGroupId.value.push(i.groupId)
      let v = 0
      if (i.type[0] === '蓝') v = 1
      else if (i.type[0] === '无') v = 2
      if (chosenTypes.value.includes(v)) continue
      chosenTypes.value.push(v)
    }

    discount({
      price: priceSum.value,
      couponGroupID: chosenGroupId.value
    }).then(res => {
      priceFin.value = res.data.result
      getUseableCoupon2()
    })

}

</script>

<template>
  <el-descriptions >
    <el-descriptions-item label="商品">{{productName}}</el-descriptions-item>
    <el-descriptions-item label="数量">{{quantity}}个</el-descriptions-item>
    <el-descriptions-item label="单价">{{price}}元</el-descriptions-item>
    <el-descriptions-item label="总价">{{priceSum}}元</el-descriptions-item>
    <el-descriptions-item label="取货方式">{{parseDelivery(delivery)}}</el-descriptions-item>
    <el-descriptions-item label="是否使用优惠券">
      <el-radio-group v-model="use" >
        <el-radio value='0' size="large">是</el-radio>
        <el-radio value='1' size="large">否</el-radio>
      </el-radio-group>
    </el-descriptions-item>
  </el-descriptions>
  <div v-if = "use === '0' && couponList.length != 0">
  <el-table
      ref="multipleTableRef"
      :data = "couponList"
      :key = "newKey"
      highlight-current-row
      :default-sort="{ prop: 'type', order: 'descending' }"
      style = "width: 100%"
      @select = "handleChange">
    <el-table-column type="selection" width="55" />
    <el-table-column property="type" label="优惠券种类" width="240" />
    <el-table-column property="scope" label="适用对象" width="120" />

  </el-table>
  <el-text v-if = "use === '0'">使用优惠券后价格: {{priceFin}}元</el-text>
  <el-divider></el-divider>
  </div>
  <div v-else-if="use === '0' && couponList.length === 0">
    <el-text>无可用优惠券</el-text>
  </div>
  <el-button @click = "payOrder" type = primary :disabled = "payDisable">支付</el-button>


</template>

<style scoped>
/deep/.el-table__header-wrapper  .el-checkbox{
  display:none
}
</style>